package com.pengxh.cmake.base

import android.app.Application
import android.util.Log
import com.pengxh.cmake.uart.SerialPort
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.utils.SaveKeyValues
import java.io.File
import java.io.IOException
import java.security.InvalidParameterException
import kotlin.properties.Delegates


class BaseApplication : Application() {

    private val kTag = "BaseApplication"
    private var serialPorts = ArrayList<SerialPort>()

    fun getSerialPorts(): ArrayList<SerialPort> = serialPorts

    fun closeSerialPort() {
        serialPorts.forEach {
            it.closeSerialPort()
        }
    }

    companion object {
        private var application: BaseApplication by Delegates.notNull()

        fun get() = application
    }

    override fun onCreate() {
        super.onCreate()
        application = this
        SaveKeyValues.initSharedPreferences(this)

        /**
         * Open the serial port
         * */
        try {
            serialPorts.apply {
                add(SerialPort(File("/dev/ttysWK1"), 9600, 0))
            }
            Log.d(kTag, "onCreate: 已初始化 ${serialPorts.size} 个串口")
        } catch (e: SecurityException) {
            "您没有串口的读写权限！".show(this)
        } catch (e: IOException) {
            "因为不明原因，串口无法打开！".show(this)
        } catch (e: InvalidParameterException) {
            "请检查串口！".show(this)
        }
    }
}